package com.taotao;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * @Package com.taotao
 * @Description:
 * @Author elwyn
 * @Date 2017/9/4 22:36
 * @Email elonyong@163.com
 */
public class HttpClient {
    @Test
    public void doGet() throws IOException {
        CloseableHttpClient aDefault = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse execute = aDefault.execute(httpGet);
        int statusCode = execute.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        HttpEntity entity = execute.getEntity();
        String s = EntityUtils.toString(entity, "utf-8");
        System.out.println(s);
        execute.close();
        aDefault.close();
    }

    @Test
    public void doGetWithParam() throws URISyntaxException, IOException {
        CloseableHttpClient aDefault = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
        uriBuilder.addParameter("query", "花千骨");
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        CloseableHttpResponse execute = aDefault.execute(httpGet);
        int statusCode = execute.getStatusLine().getStatusCode();
        System.out.println(statusCode);
        HttpEntity entity = execute.getEntity();
        String s = EntityUtils.toString(entity, "utf-8");
        System.out.println(s);
        execute.close();
        aDefault.close();
    }
}
